import { Footer } from '@/components';
import { login, getCode } from '@/services/login/loginForm';
import { AlipayCircleOutlined, TaobaoCircleOutlined, WeiboCircleOutlined } from '@ant-design/icons';
import { history, SelectLang, useModel, Helmet } from '@umijs/max';
import { Alert, Button, Form, Input, message, Space } from 'antd';
import Settings from '../../../../config/defaultSettings';
import React, { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import { createStyles } from 'antd-style';
import { encode } from 'js-base64';
import md5 from 'blueimp-md5';
import { setToken, setUser } from '@/utils/auth';

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
  };
});

const ActionIcons = () => {
  const { styles } = useStyles();

  return (
    <>
      <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.action} />
      <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.action} />
      <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.action} />
    </>
  );
};

const Lang = () => {
  const { styles } = useStyles();

  return (
    <div className={styles.lang} data-lang>
      {SelectLang && <SelectLang />}
    </div>
  );
};

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.Result>({ code: '200' });
  const [uuid, setUuid] = useState<string>('');

  const [form] = Form.useForm();
  const { initialState, setInitialState } = useModel('@@initialState');
  const [authCodeUrl, setAuthCodeUrl] = useState<string>('');

  const { styles } = useStyles();

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    setUser(userInfo);
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录

      // values.password = md5(encode(values.password));
      const res = await login({ ...values, uuid: uuid });
      setToken(res.data);
      if (res.code === '200') {
        message.success('登录成功！');
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/');
        return;
      }
      console.log(res);
      // 如果失败去设置用户错误信息
      setUserLoginState(res);
    } catch (error) {
      console.log(error);
      message.error('登录失败，请重试！');
    }
  };
  const { code } = userLoginState;
  const requestCode = async () => {
    const res = await getCode();
    setAuthCodeUrl('data:image/png;base64,' + res.img);
    setUuid(res.uuid);
  };
  useEffect(() => {
    form.setFieldValue('companyNo', 'C2206072038264650');
    form.setFieldValue('loginName', 'hk_1');
    form.setFieldValue('password', md5(encode('Aa12345678')));
    requestCode();
  }, []);
  return (
    <div className={styles.container}>
      <Helmet>
        <title>登录页 - {Settings.title}</title>
      </Helmet>
      <Lang />
      <div
        style={{
          flex: '1',
          padding: '32px 0',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        {code === 'error' && <LoginMessage content="账户或密码错误" />}
        <Form
          name="basic"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 32 }}
          form={form}
          style={{ width: 500 }}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
          autoComplete="off"
        >
          <Form.Item<API.LoginParams>
            label="油企编号"
            name="companyNo"
            rules={[{ required: true, message: '请输入油企编号！' }]}
          >
            <Input placeholder="请输入油企编号！" />
          </Form.Item>

          <Form.Item<API.LoginParams>
            label="登录名称"
            name="loginName"
            rules={[{ required: true, message: '请输入登录名称！' }]}
          >
            <Input placeholder="请输入登录名称！" />
          </Form.Item>
          <Form.Item<API.LoginParams>
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码！' }]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
          <Form.Item<API.LoginParams>
            label="验证码"
            name="code"
            rules={[{ required: true, message: '请输入验证码！' }]}
          >
            <Space.Compact block>
              <Input placeholder="请输入验证码！" />
              <img
                style={{ height: '32.0px' }}
                src={authCodeUrl}
                className="login-code-img"
                onClick={() => {
                  requestCode();
                }}
              />
            </Space.Compact>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
            <Button
              style={{ marginLeft: '20.0px' }}
              onClick={() => {
                form.resetFields();
              }}
            >
              重置{' '}
            </Button>
          </Form.Item>
        </Form>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
